package zl.tools;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class FileMoveUtil extends JFrame implements ActionListener
{
	private static final long serialVersionUID = 1L;

	public static void main(String[] args)
	{
		new FileMoveUtil();
	}

	private JLabel jlOldPathText;   
	private JLabel jlNewPathText;
	private JTextField jtfOldPath;
	private JTextField jtfNewPath;
	private JButton jbOldSelect;
	private JButton jbNewSelect;
	private JLabel jlFileTypeText;
	private JTextField jtfFileType;
	private JButton jbCopy;
	private JButton jbCut;
	private JButton jbClose;
	private JFileChooser jfcPath;
	private File oldDir;
	private boolean isEffectSub;
	private OutputStream out;
	private InputStream in;
	private ArrayList<File> files;

	public FileMoveUtil()
	{
		this.setTitle("文件迁移");   //设置窗体标题
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //设置窗体的默认关闭操作
		this.setSize(400,180);  //设置窗体的大小
		this.setLocation(    //定位窗体到屏幕中间
			this.getToolkit().getScreenSize().width / 2 - this.getWidth() / 2,
			this.getToolkit().getScreenSize().height / 2 - this.getHeight() / 2
		);
		this.setResizable(false);   //设置窗体大小不可变
		this.setLayout(new GridLayout(4,1));   //设置窗体的布局（4行1列）

		//初始化对像
		this.jlOldPathText = new JLabel(" 原路径：");
		this.jlNewPathText = new JLabel(" 新路径：");
		this.jlFileTypeText = new JLabel("文件类型：");
		this.jtfOldPath = new JTextField(23);  //实例化文本框
		this.jtfOldPath.setEnabled(false);     //设置文本框为不可编辑状态
		this.jtfNewPath = new JTextField(23);
		this.jtfNewPath.setEnabled(false);
		this.jtfFileType = new JTextField(5);
		this.jbOldSelect = new JButton("选择");    //实例化按钮
		this.jbOldSelect.addActionListener(this);  //给按钮注册事件
		this.jbNewSelect = new JButton("选择");
		this.jbNewSelect.addActionListener(this);
		this.jbCopy = new JButton("复制");
		this.jbCopy.addActionListener(this);
		this.jbCut = new JButton("剪切");
		this.jbCut.addActionListener(this);
		this.jbClose = new JButton("关闭");
		this.jbClose.addActionListener(this);
		String defaultPath = null;  
		try
		{
			//获取当前路径的方法
			/*  
			System.out.println(FormMain.class.getResource(""));
			System.out.println(FormMain.class.getResource("/"));
			System.out.println(FormMain.class.getResource("").getPath());
			System.out.println(FormMain.class.getResource("").toURI().getPath());
			System.out.println(FormMain.class.getResource("").toURI().toString());
			System.out.println(new File(FormMain.class.getResource("").toURI().getPath()).isDirectory());
			*/
			defaultPath = FileMoveUtil.class.getResource("").toURI().getPath();
		}
		catch (URISyntaxException e)
		{
			e.printStackTrace();
		}
		
		//根据默认地址实例化文件选择器对像
		this.jfcPath = new JFileChooser(defaultPath);  
		//设置文件选择器对像只能选择目录
		this.jfcPath.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);  

		//将对像添加到窗体并设置布局方式
		JPanel temp = new JPanel();
		temp.setLayout(new FlowLayout(FlowLayout.LEFT));
		temp.add(this.jlOldPathText);
		temp.add(this.jtfOldPath);
		temp.add(this.jbOldSelect);
		this.add(temp);

		temp = new JPanel();
		temp.setLayout(new FlowLayout(FlowLayout.LEFT));
		temp.add(this.jlNewPathText);
		temp.add(this.jtfNewPath);
		temp.add(this.jbNewSelect);
		this.add(temp);
		
		temp = new JPanel();
		temp.setLayout(new FlowLayout(FlowLayout.LEFT));
		temp.add(this.jlFileTypeText);
		temp.add(this.jtfFileType);
		temp.add(new JLabel("(输入要操作的文件类型，如：txt|MP3|...)"));
		this.add(temp);

		temp = new JPanel();
		temp.setLayout(new FlowLayout(FlowLayout.RIGHT));
		temp.add(this.jbCopy);
		temp.add(this.jbCut);
		temp.add(this.jbClose);
		this.add(temp);

		this.setVisible(true);
	}

	//检查
	public boolean check()
	{
		String text = null;
		if(this.jtfOldPath.getText().equals(""))
		{
			text = "请选择旧路径！！！";
		}
		else if(this.jtfNewPath.getText().equals(""))
		{
			text = "请选择新路径！！！";
		}
		else if(this.jtfFileType.getText().equals(""))
		{
			text = "请输入文件路径！！！";
		}
		else if(this.jtfNewPath.getText().substring(0,
			this.jtfNewPath.getText().lastIndexOf(File.separator)).indexOf(
			this.jtfOldPath.getText()) != -1 || 
			this.jtfOldPath.getText().equals(this.jtfNewPath.getText()))
		{	
			text = "新路径不能被旧路径所包含！！！";
		}
		else
		{
			if(JOptionPane.showConfirmDialog(this,"是否影响子文件夹？",
				"消息",JOptionPane.YES_NO_OPTION) == 0)
			{
				this.isEffectSub = true;
			}
			return true;
		}
		JOptionPane.showMessageDialog(this,text,"消息",JOptionPane.INFORMATION_MESSAGE);
		return false;
	}

	//获取要操作的文件名
	public void getFiles(File dir)
	{
		for(File f : dir.listFiles())
		{
			if(f.isDirectory())
			{
				if(isEffectSub)
				{
					//如果影响子文件夹则递归调用本方法
					this.getFiles(f);
				}
			}
			else
			{
				if(f.getPath().substring(f.getPath().lastIndexOf(".")
					+ 1).equals(jtfFileType.getText()))
				{
					//将指定类型的文件添加到集合
					this.files.add(f);
				}
			}
		}
	}

	public String getNewName(File f)
	{
		StringBuffer str = new StringBuffer(
			f.getName().substring(0,f.getName().lastIndexOf(".")) + "--");
		File te = f.getParentFile();
		do
		{
			if(te != null)
			{
				if(te.getName().length() != 0)
					str.append("-" + te.getName());
				te = te.getParentFile();
			}
			else
			{
				str.append("-" + f.getPath().substring(0,1));
				break;
			}
		}
		while (true);
		return str.toString();
	}

	//复制方法
	public boolean copy()
	{
		this.files = new ArrayList<File>();
		this.getFiles(this.oldDir);
		if(this.files.size() == 0)
		{
			JOptionPane.showMessageDialog(this,"未找到此类型文件！！！",
				"消息",JOptionPane.INFORMATION_MESSAGE);
			return false;
		}
		for(File file : this.files)
		{
			try
			{
				File f = new File(this.jtfNewPath.getText() + 
					File.separator + file.getName());
				//*  //如果有同名文件存在。则重命名
				//方法一
				int i = 1;
				do
				{
					if(f.exists())
					{
						f = new File(this.jtfNewPath.getText() + 
					File.separator + file.getName().substring(0,
							file.getName().lastIndexOf(".")) + "(" + i + ")" + 
							file.getName().substring(file.getName().lastIndexOf(".")));
						i++;
					}
					else
					{
						break;
					}
				}
				while (true);
				/*/
				/*
				//方法二
				if(f.exists())
				{
					f = new File(this.jtfNewPath.getText() + 
						File.separator + this.getNewName(file) + 
						f.getName().substring(f.getName().lastIndexOf(".")));
				}
				*/
				//文件输出流
				out = new FileOutputStream(f);
				//文件输入流
				in = new FileInputStream(file);
				int temp = 0;
				byte[] b = new byte[1024*1024]; //一次操作1兆
				//复制文件
				while((temp = in.read(b)) != -1)
				{
					out.write(b,0,temp);
				}
			}
			catch (FileNotFoundException e)
			{
				JOptionPane.showMessageDialog(this,"文件不存在！！！",
				"消息",JOptionPane.INFORMATION_MESSAGE);
				e.printStackTrace();
				return false;
			}			
			catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
			finally
			{
				try
				{
					//关闭文件操作流
					if(out != null)
					{
						out.close();
					}
					if(in != null)
					{
						in.close();
					}
				}
				catch (IOException e)
				{
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}

	//剪切方法
	public boolean cut()
	{
		if(!this.copy())
		{
			return false;
		}
		for(File file : files)
		{
			file.delete();
		}
		return true;
	}

	//重写ActionListener接口的方法
	public void actionPerformed(ActionEvent e)
	{
		JButton jb = (JButton)e.getSource();
		//单击原路径后的选择按钮时
		if(jb == this.jbOldSelect)
		{
			if(this.jfcPath.showOpenDialog(this) == 0)
			{
				this.jtfOldPath.setText(this.jfcPath.getSelectedFile().toString());		
				this.jtfOldPath.setToolTipText(this.jfcPath.getSelectedFile().toString());
				this.oldDir = new File(this.jfcPath.getSelectedFile().toString());
			}
		}
		//单击新路径后的选择按钮时
		else if(jb == this.jbNewSelect)
		{
			if(this.jfcPath.showOpenDialog(this) == 0)
			{
				this.jtfNewPath.setText(this.jfcPath.getSelectedFile().toString());		
				this.jtfNewPath.setToolTipText(this.jfcPath.getSelectedFile().toString());
			}
		}
		//单击复制按钮时
		else if(jb == this.jbCopy)
		{
			if(!this.check())
			{
				return;
			}
			String msg = null;
			this.setEnabled(false);
			if(this.copy())
			{
				msg = "操作成功！！！";
			}
			else
			{
				msg = "操作失败！！！";
			}
			JOptionPane.showMessageDialog(this,msg,
				"消息",JOptionPane.INFORMATION_MESSAGE);
			this.setEnabled(true);
		}
		//单击剪切按钮时
		else if(jb == this.jbCut)
		{
			if(!this.check())
			{
				return;
			}
			String msg = null;
			this.setEnabled(false);
			if(this.cut())
			{
				msg = "操作成功！！！";
			}
			else
			{
				msg = "操作失败！！！";
			}
			JOptionPane.showMessageDialog(this,msg,
				"消息",JOptionPane.INFORMATION_MESSAGE);
			this.setEnabled(true);
		}
		//单击关闭按钮时
		else
		{
			System.exit(1);
		}
	}
}